package com.mvu.banana.guest.client;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.mvu.banana.common.client.AsyncCallbackAdapter;
import com.mvu.banana.common.client.CommonComposite;
import com.mvu.banana.common.client.SystemConstants;
import com.mvu.banana.guest.client.gen.LoginPanelDTO;
import com.mvu.banana.user.client.Tiles;

/**
 * @generate-server-code
 */
public class LoginPanel extends CommonComposite<LoginPanelDTO> implements SystemConstants {
  interface LoginPanelUiBinder extends UiBinder<HTMLPanel, LoginPanel> {
  }

  private static LoginPanelUiBinder binder = GWT.create(LoginPanelUiBinder.class);

  /**
   * @see java.lang.String
   * @Min 2
   * @Max 30
   **/
  @UiField
  public TextBox emailInput;

  /**
   * @see java.lang.String
   * @Min 2
   * @Max 30
   */
  @UiField
  public PasswordTextBox passwordInput;
  /**
   * @output
   */
  public String username;
  /**
   * @output
   */
  public String errorMessage;
  @UiField
  Button loginButton;
  @UiField
  CheckBox rememberMe;
  @UiField
  Anchor recoverPasswordLink;

  final long DURATION = 1000 * 60 * 60 * 24 * 14; //duration remembering login: 2 weeks

  public LoginPanel() {
    super(new LoginPanelDTO());
    initWidget(binder.createAndBindUi(this));
  }

  @UiHandler("loginButton")
  public void login(ClickEvent event) {
    login();
  }

  public void login() {
    post(loginButton, new AsyncCallbackAdapter<LoginPanelDTO>(loginButton) {
      @Override
      protected void afterUpdate(LoginPanelDTO dto) {
        if (dto.username != null) {
          Date expires = new Date(System.currentTimeMillis() + DURATION);
          Cookies.setCookie(USERNAME, dto.username, expires);
          new Tiles().go();
        } else {
          passwordInput.setText("");
          showError(dto.errorMessage);
        }
      }
    });
  }

  @UiHandler("passwordInput")
  public void login(KeyUpEvent event) {
    if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
      login();
    }
  }
}